# -*- coding: utf-8 -*-
__author__ = 'Paul'
import random
from zope import schema
from zope.formlib import form
from zope.interface import implements
from zope.component import getMultiAdapter
from plone.app.portlets.portlets import base
from plone.memoize.instance import memoize
from plone.portlets.interfaces import IPortletDataProvider
from zope.component import getUtility, queryUtility

from DateTime import DateTime
from Products.Five.browser.pagetemplatefile import\
    ViewPageTemplateFile
from Products.CMFCore.utils import getToolByName
from Products.bpContents import _
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm

from plone.memoize.compress import xhtml_compress
from Products.bpContents.articulo import IArticulo
from Products.bpContents.galeria import IGaleria
from Products.bpContents.evento import IEvento
from zope.schema.interfaces import IVocabularyFactory

from zope.site.hooks import getSite
import unicodedata
from intereses_portlets import CanalesVocabularyFactory
from Acquisition import aq_parent,aq_base,aq_inner

from OFS.interfaces import IOrderedContainer
from Products.ATContentTypes.interfaces.image import IATImage

from Products.bpContents.portlets.intereses_portlets import CanalesVocabularyFactory

class IUltimosPortlet(IPortletDataProvider):
    count = schema.Int(title=(u'Cantidad'),
        description=(u'Número de items a mostrar.'),
        required=True,
        default=3)

    prioridad = schema.Choice(
        title=_(u"Prioridad"),
        description=(u'Canal que tienen prioridad para el destacado.'),
        vocabulary='bp.CanalesVocab',
        required=False,
        )

class Assignment(base.Assignment):
    implements(IUltimosPortlet)

    def __init__(self, count=5, prioridad="sin prioridad"):
        self.count = count
        self.prioridad=prioridad

    @property
    def title(self):
        cadena="Ultimos publicados"
        return cadena


class Renderer(base.Renderer):
    ##_template = ViewPageTemplateFile('intereses_portlet.pt')
    render = ViewPageTemplateFile('ultimos_portlet.pt')

    def __init__(self, *args):
        base.Renderer.__init__(self, *args)
        self.prioridad=self.data.prioridad
        context = aq_inner(self.context)
        portal_state = getMultiAdapter((context, self.request), name=u'plone_portal_state')
        self.anonymous = portal_state.anonymous()
        self.portal_url = portal_state.portal_url()
        self.typesToShow = portal_state.friendly_types()
        plone_tools = getMultiAdapter((context, self.request), name=u'plone_tools')
        self.catalog = plone_tools.catalog()
        self.portal = getMultiAdapter((self.context, self.request),name=u'plone_portal_state').portal()

    @property
    def available(self):
        return True

    def getArticulos(self):
        tienePrioridad = self.data.prioridad
        posta=self._data()

        return posta

    @memoize
    def _data(self):
        from Products.bpContents.utils import Utilidades

        uti=Utilidades()
        total=uti.dameNovedades(self.context,self.request,self.catalog,self.data.count)

        return total

    @memoize
    def getContainer(self, path):
        if not path:
            return None
        if path.startswith('/'):
            path = path[1:]
        if not path:
            return None

        return aq_inner(self.portal).restrictedTraverse(path, default=None)

    def get_position_in_parent(self,objId):
        """ Use IOrderedContainer interface to extract the object's manual ordering position
        """
        obj=self.catalog(id=objId)[0]
        parent = obj.aq_inner.aq_parent
        ordered = IOrderedContainer(parent, None)

        if ordered is not None:
            return ordered.getObjectPosition(objId)
        return 0





class AddForm(base.AddForm):
    form_fields = form.Fields(IUltimosPortlet)
    label = _(u"Add Recent Portlet")
    description = _(u"This portlet displays recently modified content.")

    def create(self, data):
        return Assignment(count=data.get('count', 3),prioridad=data.get('prioridad','sin prioridad'))

class EditForm(base.EditForm):
    form_fields = form.Fields(IUltimosPortlet)
    label = _(u"Edit Recent Portlet")
    description = _(u"This portlet displays recently modified content.")